<style scoped>
.img-face {
  max-width: 200px;
  max-height: 200px;
  padding: 10px;
  cursor: pointer;
}
</style>
<template>
  <div>

    <Form class="form-more" ref="formValidate" :model="tempData" :label-width="80" :rules="ruleValidate">
      <Row :gutter="16">
        <Col span="8">
        <FormItem label="单据日期" prop="OrderDate">
          <DatePicker :clearable="false" type="date" format="yyyy年MM月dd日" v-model="tempData.OrderDate" :readonly="isReadOnly"></DatePicker>
        </FormItem>
        </Col>
        <Col span="8">
        <FormItem label="客户名称" prop="CustomerId">
          <Input v-model="tempData.CustomerId" style="display:none">

          </Input>
          <Input v-model="tempData.CustomerName" readonly>
          <Icon type="ios-more" v-if="!isReadOnly" size="32" style="cursor: pointer" slot="suffix" @click="choseCustomer()" />
          </Input>
        </FormItem>
        </Col>
        <Col span="3" v-if="!isReadOnly">
        <Button type="primary" @click="choseProduct()" icon="md-add">选择商品</Button>
        </Col>
        <Col span="3" v-if="!isReadOnly">
        <Button type="primary" @click="choseOrder()" icon="md-add">选择销售单</Button>
        </Col>
        <Col span="3" v-if="isReadOnly">
        <Button type="primary" @click="GetSaleOrderBackAndPrint(Id)" icon="md-print">打印</Button>
        </Col>
      </Row>
      <vxe-table style="margin-bottom: 10px" border ref="xTable" resizable show-overflow height="400px" align="center"
        :edit-rules="validRules" :data="tempDetail" show-footer :footer-method="footerMethod" :edit-config="!isReadOnly?{
          trigger: 'click',
          mode: 'row',
          showIcon: false,
          autoClear: false,
        }:null">
        <vxe-column type="seq" width="60" title="序号">

        </vxe-column>

        <vxe-column field="ProductName" title="商品">

        </vxe-column>

        <vxe-column field="Num" width="150" title="数量" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.Num" type="number" @change="updateFooterEvent"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="Unit" width="100" title="单位">

        </vxe-column>
        <vxe-column field="Price" width="150" title="单价(元)" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.Price" type="number" @change="updateFooterEvent"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="Amount" width="150" title="金额(元)" :edit-render="{}">
          <template #edit="{ row }">
            <span>{{ countAmount(row) }} </span>
          </template>
        </vxe-column>
        <vxe-column field="Remark" title="备注" :edit-render="{}">
          <template #edit="{ row }">
            <vxe-input v-model="row.Remark" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column v-if="!isReadOnly" title="操作" width="80">
          <template #default="{ seq }">
            <Button size="small" type="error" @click="removeRowEvent(seq)">删除</Button>
          </template>
        </vxe-column>
      </vxe-table>
      <Row>

        <Col span="5">
        <FormItem label="减扣费用" prop="GiveupFee">
          <Input v-model="tempData.GiveupFee" type="number" :readonly="isReadOnly"> <span slot="append">元</span>
          </Input>
        </FormItem>
        </Col>
        <Col span="5">
        <FormItem label="退款金额" prop="AllFee">
          <Input v-model="AllFee" readonly type="number"> <span slot="append">元</span>
          </Input>
        </FormItem>
        </Col>
        <Col span="5">
        <FormItem label="实际退款" prop="PayFee">
          <Input v-model="tempData.PayFee" type="number" :readonly="isReadOnly"> <span slot="append">元</span>
          </Input>
        </FormItem>
        </Col>
      </Row>

      <FormItem label="备注" prop="Remark">
        <Input v-model="tempData.Remark" :readonly="isReadOnly" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" />
      </FormItem>
      <FormItem label="是否打印" v-if="!isReadOnly">
        <RadioGroup size="large" v-model="isPrint">
          <Radio :label="0">否</Radio>
          <Radio :label="1">是</Radio>
        </RadioGroup>
      </FormItem>
    </Form>
    <div class="div-footer" v-if="!isReadOnly">
      <Button type="text" @click="cancel()">取消</Button>
      <Button type="primary" :loading="loading" @click="SaveSaleOrderBack">确定</Button>
    </div>
    <Modal :footer-hide="true" :width="800" draggable v-model="modalCustomer" title="选择客户" :mask-closable="false">
      <customerchose v-if="modalCustomer" @on-success="getCustomer" />
    </Modal>
    <Modal :footer-hide="true" :width="1000" draggable v-model="modalProduct" title="选择商品" :mask-closable="false">
      <productchose v-if="modalProduct" @on-success="getProduct" />
    </Modal>
    <Modal :footer-hide="true" :width="1000" draggable v-model="modalOrder" title="选择销售单商品" :mask-closable="false">
      <saleorderchose v-if="modalOrder" @on-success="getOrder" />

    </Modal>
    <iframe id="iframe-print" frameborder="0" style="display: none" scrolling="auto" :src="printSrc"></iframe>
  </div>
</template>

<script>
import {
  SearchProduct,
  GetSaleOrderBack,
  GetSaleOrderBackAndPrint,
  SaveSaleOrderBack
} from '@/api/saleorderback'
import customerchose from '../customer/customerchose.vue'
import productchose from '../product/productchose.vue'
import saleorderchose from '../saleorder/saleorderchose.vue'
import { GetSystemConfig } from '@/api/data'
export default {
  name: 'saleorderbackedit',
  props: ['Id', 'Type'],
  components: {
    customerchose, productchose, saleorderchose
  },
  data () {
    return {
      Extras: {},
      printSrc: '/static/print/saleorderback.html?temp=' + Date.parse(new Date()),

      tableHeight: 450,

      loading: false,
      tempData: {

      },
      isPrint: 0,
      modalTemp: false,
      tempDetail: [],
      validRules: {
        ProductName: [{ required: true, message: '不能为空', trigger: 'manual' }],
        Weight: [{ required: true, message: '不能为空', trigger: 'manual' }],
        Price: [{ required: true, message: '不能为空', trigger: 'manual' }]
      },
      modalCustomer: false,
      modalProduct: false,
      modalOrder: false,
      configData: {},
      dataProduct: [],
      ruleValidate: {

      }

    }
  },

  computed: {
    isReadOnly () {
      return this.Type == 1
    },
    AllFee () {
      let vm = this
      var amount = 0
      if (vm.configData.config4 == 1) {
        this.tempDetail.forEach((item) => {
          if (item.Price && item.Num) {
            amount += Math.floor(Number(item.Price) * Number(item.Num))
          }
        })
        if (this.tempData.FreightFee) {
          amount += Number(this.tempData.FreightFee)
        }

        if (this.tempData.GiveupFee) {
          amount -= Number(this.tempData.GiveupFee)
        }
        return Math.floor(amount)
      } else {
        this.tempDetail.forEach((item) => {
          if (item.Price && item.Num) {
            amount += Number(item.Price) * Number(item.Num)
          }
        })
        if (this.tempData.FreightFee) {
          amount += Number(this.tempData.FreightFee)
        }
        if (this.tempData.GiveupFee) {
          amount -= Number(this.tempData.GiveupFee)
        }
        return amount.toFixed(2)
      }
    }
  },

  methods: {
    cancel () {
      this.$emit('on-success', 0)
    },
    handleSummary ({ columns, data }) {
      let vm = this
      const sums = {}
      columns.forEach((column, index) => {
        const key = column.key
        if (index === 0) {
          sums[key] = {
            key,
            value: '合计'
          }
        } else if (key == 'Amount') {
          sums[key] = {
            key,
            value: Number(vm.Extras.Amount.toFixed(2))
          }
        } else if (key == 'FreightFee') {
          sums[key] = {
            key,
            value: Number(vm.Extras.FreightFee.toFixed(2))
          }
        } else if (key == 'GiveupFee') {
          sums[key] = {
            key,
            value: Number(vm.Extras.GiveupFee.toFixed(2))
          }
        } else if (key == 'AllFee') {
          sums[key] = {
            key,
            value: Number(vm.Extras.AllFee.toFixed(2))
          }
        } else if (key == 'PayFee') {
          sums[key] = {
            key,
            value: Number(vm.Extras.PayFee.toFixed(2))
          }
        } else {
          sums[key] = {
            key,
            value: ' '
          }
        }
      })

      return sums
    },
    handleSearch (value) {
      if (!value.trim()) {
        return
      }
      let vm = this
      var reqData = {
        page: 1,
        size: 15,
        keyword: value
      }
      SearchProduct(reqData).then((res) => {
        var data = res.data
        if (data.StatusCode == 200) {
          vm.dataProduct = data.Data.Items.map((x) => x.Name)
        }
      })
    },
    countAmount (row) {
      let vm = this
      if (row.Price && row.Num) {
        if (vm.configData.config4 == 1) {
          row.Amount = Math.floor(row.Price * row.Num)
        } else {
          row.Amount = row.Price * row.Num
        }
      } else {
        row.Amount = 0
      }

      return row.Amount
    },

    removeRowEvent (seq) {
      var index = seq - 1
      console.log(index)
      this.tempDetail.splice(index, 1)
    },

    updateFooterEvent () {
      setTimeout(() => {
        const $table = this.$refs.xTable
        $table.updateFooter()
      }, 100)
    },
    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 0) {
            return '合计'
          }
          if (['Num', 'Amount'].includes(column.property)) {
            return this.sumNum(data, column.property)
          }
          return null
        })
      ]
    },
    sumNum (list, field) {
      let count = 0
      list.forEach((item) => {
        count += Number(item[field])
      })
      return count
    },
    choseCustomer () {
      this.modalCustomer = true
    },
    getCustomer (data) {
      let vm = this
      vm.modalCustomer = false
      vm.tempData.CustomerName = data.Name
      vm.tempData.CustomerId = data.Id
    },
    choseProduct () {
      this.modalProduct = true
    },
    choseOrder () {
      this.modalOrder = true
    },
    getProduct (data) {
      let vm = this
      vm.modalProduct = false
      var choseArr = []
      data.forEach(e => {
        var has = false
        vm.tempDetail.forEach(s => {
          if (e.Id == s.ProductId) {
            has = true
          }
        })
        if (!has) {
          choseArr.push({
            ProductId: e.Id,
            ProductName: e.Name,
            ProductCode: e.Code,
            Unit: e.Unit,
            Specification: e.Specification,
            Num: 1,
            Price: e.Price,
            Amount: e.Price,
            Remark: ''
          })
        }
      })

      vm.tempDetail = vm.tempDetail.concat(choseArr)
    },
    getOrder (data) {
      let vm = this
      vm.modalOrder = false
      if (!vm.tempData.CustomerId) {
        vm.tempData.CustomerName = data.order.CustomerName
        vm.tempData.CustomerId = data.order.CustomerId
      }
      vm.tempDetail = data.detail
    },
    async SaveSaleOrderBack () {
      let vm = this
      const $table = this.$refs.xTable
      const errMap = await $table.validate(true).catch((errMap) => errMap)
      if (errMap) {
        console.log('验证失败')
        return
      }

      if (typeof vm.tempData.OrderDate === 'object') {
        vm.tempData.OrderDate = vm
          .dayjs(vm.tempData.OrderDate)
          .format('YYYY年MM月DD日')
      }
      if (!vm.tempData.OrderDate) {
        this.$Message.warning('日期不能为空')
        return
      }
      if (!vm.tempData.CustomerId) {
        this.$Message.warning('客户不能为空')
        return
      }

      vm.tempData.FreightFee = Number(vm.tempData.FreightFee)
      vm.tempData.GiveupFee = Number(vm.tempData.GiveupFee)
      vm.tempData.PayFee = Number(vm.tempData.PayFee)
      var reqData = {
        order: vm.tempData,
        detail: vm.tempDetail
      }
      vm.loading = true
      SaveSaleOrderBack(reqData).then((res) => {
        vm.loading = false
        const data = res.data
        if (data.StatusCode == 200) {
          vm.modalTemp = false
          vm.$Message.success({ title: '提示', content: '保存成功' })
          if (vm.isPrint) {
            vm.GetSaleOrderBackAndPrint(data.Data)
          }
          vm.$emit('on-success', 1)
        } else {
          vm.$Message.error({ title: '提示', content: data.Errors })
        }
      })
    },
    GetSaleOrderBack () {
      let vm = this
      GetSaleOrderBack(this.Id).then((res) => {
        const data = res.data
        if (data.StatusCode == 200) {
          vm.tempData = data.Data.order
          vm.tempDetail = data.Data.detail
        } else {
          this.$Message.error({ title: '提示', content: data.Errors })
        }
      })
    },
    GetSaleOrderBackAndPrint (id) {
      GetSaleOrderBackAndPrint(id).then((res) => {
        const data = res.data
        if (data.StatusCode == 200) {
          document
            .getElementById('iframe-print')
            .contentWindow.printData(data.Data)
        } else {
          this.$Message.error({ title: '提示', content: data.Errors })
        }
      })
    },

    GetSystemConfig () {
      let vm = this
      GetSystemConfig().then((res) => {
        const data = res.data
        if (data.StatusCode == 200) {
          vm.configData = data.Data
        } else {
          Message.error({ title: '提示', content: data.Errors })
        }
      })
    }
  },
  mounted () {
    this.tempData.OrderDate = this.dayjs().format('YYYY年MM月DD日')
    this.GetSystemConfig()
    if (this.Id > 0) {
      this.GetSaleOrderBack()
    }
  }
}
</script>

<style>
</style>
